const { models } = require('../model')
const { toUpper } = require('lodash')

// 处理用户日志
async function process (ctx, doc) {
  if (toUpper(ctx.method) === 'GET' && doc) {
    // 游客、非owner的访问才计数
    if (ctx._user === undefined || (ctx._user._id.toString() !== doc.createUserId.toString())) {
      models.Article.updateOne({
        _id: doc._id
      }, {
        $inc: { 'statistics.reads': 1 }
      }, { multi: false })
    }
  }
}

async function getKmSpace (userId) {
  const doc = await models.KmSpace.findOne({
    userId: userId,
    type: 2
  })
  return doc
}

async function initKmSpace (userId) {
  const doc = await getKmSpace(userId)
  if (doc) return

  const ret = await models.KmSpace.insertOne({
    name: '个人空间',
    userId: userId,
    type: 2,
    status: 1
  })
  const kmSpaceId = ret.insertedId
  await models.User.updateOne(
    { _id: userId },
    { $set: { kmSpaceId: kmSpaceId } }
  )

  //
  const homepageId = initKmSpaceHomepage(kmSpaceId, userId)
  await models.KmSpace.updateOne(
    { _id: kmSpaceId },
    { $set: { homepageId: homepageId } }
  )
}

async function initKmSpaceHomepage (kmSpaceId, userId) {
  const doc = {
    createUserId: userId,
    status: 6,
    type: 1,
    createWay: 5,
    contentForm: 1,
    title: 'Homepage',
    content: '',
    statistics: { shows: 0, reads: 0, likes: 0, collects: 0, shares: 0, votes: 0 },
    parentId: '',
    kmSpaceId: kmSpaceId
  }
  const ret = await models.Article.insertOne(doc)
  return ret.insertedId
}

module.exports = {
  process,
  initKmSpace,
  getKmSpace,
  initKmSpaceHomepage
}
